package liangtWorkSpace.threadDemo.thread.JUC;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author liangt
 * @ClassName: ThreadPoolSimpal
 * @title: ThreadPoolSimpal
 * @projectName liangtWorkSpace.threadDemo.thread.JUC
 * @description: TODO
 * @date 2020/11/5 13:03
 */
public class ThreadPoolSimpal {

    public static void main(String[] args) {
        //创建一个缓存线程池
        ExecutorService executorService1 =getThreadPool(1);
        ExecutorService executorService2 =getThreadPool(2);
        ExecutorService executorService3 =getThreadPool(3);
        ExecutorService executorService4 =getThreadPool(4);

        for (int i = 0; i < 1000; i++) {
            final int index = i;
            executorService1.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":" + index);
                }
            });
        }
        for (int i = 0; i < 1000; i++) {
            final int index = i;
            executorService3.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":" + index);
                }
            });
        }
        //等待线程池所有线程运行完进行关闭
        executorService1.shutdown();
        //强制关闭线程池，不等的所有线程运行完毕
//        executorService.shutdownNow();
    }

    private static ExecutorService getThreadPool(int type) {
        ExecutorService executorService = null;
        switch (type) {
            //缓存线程池
            case 1:
                executorService = Executors.newCachedThreadPool();
                break;
            case 2:
                //指定数量缓存池
                executorService = Executors.newFixedThreadPool(5);
                break;
            case 3:
                //单线程池
                executorService = Executors.newSingleThreadExecutor();
                break;
            default:
                executorService = Executors.newCachedThreadPool();
                break;
        }
        return executorService;
    }
}
